# Create your views here.
from dev.synchronicity.models import *
from django import newforms as forms
from django.newforms import widgets

from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group, User
from django.contrib import auth

def login(request):
	""" Gives the ability to login to the site """
	if request.method == 'POST':
		username = request.POST['username']
		password = request.POST['password']
		user = auth.authenticate(username=username, password=password)
		if user is not None and user.is_active:
			# Correct password, and the user is marked as "active"
			auth.login(request, user)
			# Redirect to a success page.
			return HttpResponseRedirect('/accounts/home')
		else:
			t = loader.get_template('login.html')
			c = Context(
				{'error': True,
				 'username': username})
			return HttpResponse(t.render(c))
	else:
		t = loader.get_template('login.html')
		c = Context()
		return HttpResponse(t.render(c))



def logout(request):
	""" Logs the user out of the site """
	auth.logout(request)
	# Redirect to a success page.
	return HttpResponseRedirect("/accounts/loggedout/")


@login_required
def listProjects(request):
	""" Returns a list of all the projects"""
	
	# Get all the projects
	projects = Project.objects.all()

	
	t = loader.get_template('view/list.html')
	c = Context({'projects': projects})
	return HttpResponse(t.render(c))

@login_required
def viewProject(request, project_id):
	project = Project.objects.get(pk=project_id)
		
	# Get all the objectives related to that project
	objectives = Objective.objects.filter(project=project)
	
	t = loader.get_template('view/project.html')
	c = Context(
		{'project': project,
		 'objectives': objectives,
		})
	return HttpResponse(t.render(c))

@login_required
def viewObjective(request, objective_id):
	
	obj = Objective.objects.get(pk=objective_id)
	
	t = loader.get_template('view/objective.html')
	c = Context({'obj': obj})
	return HttpResponse(t.render(c))

@login_required
def loggedin(request):
	""" User has logged in """
	username = request.user.get_full_name()
	usergroup = request.user.groups.get().name
	projects = Project.objects.filter(lead=request.user)
		
	# Get all the projects created this month
	from datetime import date
	today = date.today().month
	newProjects = Project.objects.filter(request_date__month=today)
	
	# Get all the active projects
	
	t = loader.get_template('home.html')
	c = Context({
		'username': username,
		'projects': projects,
		'newprojects': newProjects
		})
	return HttpResponse(t.render(c))

@login_required
def addProject(request):
    """ Adds a project """
    t = loader.get_template('add_project.html')
    context = {}
    
    # Set up the options for the form
    client = Group.objects.filter(name='Client')[0]
    context['clients'] = User.objects.filter(groups=client)
    developer = Group.objects.filter(name='Developer')[0]
    context['developers'] = User.objects.filter(groups=developer)
    
    if request.method == 'POST':
        context['error'] = False
        context['title'] = request.POST['title']
        context['client'] = request.POST['client']
        context['lead'] = request.POST['lead']
        context['overview'] = request.POST['overview']
        
        # Some very simple validation to make sure all
        # the fields of the form are filled in.
        if context['title'] == u'':
            context['error'] = True
            context['error_title'] = u'Title is required'
                   
        if context['client'] == u'x':
            context['error'] = True
            context['error_client'] = u'Client is required'

        if context['lead'] == u'x':
            context['error'] = True
            context['error_lead'] = u'Client is required'
        
        if context['overview'] == u'':
            context['error'] = True
            context['error_overview'] = u'Overview is required'
        
        if context['error']:
            c = Context(context)
            return HttpResponse(t.render(c))     
        else:
            from datetime import date        	
            p = Project(title=context['title'],
                        overview=context['overview'],
        	            request_date=datetime.today(),
        	            client=context['client'],
        	             lead=context['lead'],
        	             creator=user,
        	             active=False)
            # Redirect to the newly created project
            return HttpResponseRedirect('/accounts/add-project') 
    else:
        c = Context(context)
        return HttpResponse(t.render(c))